package com.woniuxy.patrol.service.impl;

import com.woniuxy.common.utils.ResponseUtil;
import com.woniuxy.patrol.mapper.CommunityMapper;
import com.woniuxy.patrol.pojo.Community;
import com.woniuxy.patrol.service.CommunityService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CommunityServiceImpl implements CommunityService {

    @Resource
    private CommunityMapper communityMapper;

    @Override
    public List<Community> getAllCommunities() {
        return communityMapper.selectAllCommunities();
    }

    @Override
    public Community getCommunityById(Long id) {
        return communityMapper.selectById(id);
    }

    @Override
    @Transactional
    public ResponseUtil addCommunity(Community community) {
        // 参数校验
        if (community.getName() == null || community.getName().trim().isEmpty()) {
            return ResponseUtil.error("社区名称不能为空");
        }

        // 检查社区编号是否已存在
        // （实际项目中应添加唯一编号校验）

        // 设置默认值
        community.setIsDelete(1); // 默认存在
        int result = communityMapper.insert(community);
        if (result > 0) {
            return ResponseUtil.success("添加社区成功");
        }
        return ResponseUtil.error("添加社区失败");
    }

    @Override
    @Transactional
    public ResponseUtil updateCommunity(Community community) {
        // 参数校验
        if (community.getId() == null) {
            return ResponseUtil.error("社区ID不能为空");
        }

        // 检查社区是否存在
        Community existCommunity = communityMapper.selectById(community.getId());
        if (existCommunity == null || existCommunity.getIsDelete() == 0) {
            return ResponseUtil.error("社区不存在");
        }

        int result = communityMapper.updateById(community);
        if (result > 0) {
            return ResponseUtil.success("更新社区成功");
        }
        return ResponseUtil.error("更新社区失败");
    }

    @Override
    @Transactional
    public ResponseUtil deleteCommunity(Long id) {
        // 检查社区是否存在
        Community existCommunity = communityMapper.selectById(id);
        if (existCommunity == null || existCommunity.getIsDelete() == 0) {
            return ResponseUtil.error("社区不存在");
        }

        // 逻辑删除：设置is_delete=0
        existCommunity.setIsDelete(0);
        int result = communityMapper.updateById(existCommunity);
        if (result > 0) {
            return ResponseUtil.success("删除社区成功");
        }
        return ResponseUtil.error("删除社区失败");
    }
}